
from typing import Optional
from fastapi import APIRouter, Depends
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from app.db import get_db
from app.utils.response import BaseRes
from app.service.compute.add import get_compute_creator
from app.service.compute.delete import get_compute_deleter
from app.service.compute.scale import get_compute_scaler
from app.service.compute.list import get_compute_lister
from app.controller.model.compute import AddComputeReq, AddComputeRes, DeleteComputeReq, ScaleComputeReq, ScaleComputeRes

compute_router = APIRouter()


@compute_router.get('/compute')
def get_compute_list(page: int = 1, size: int = 20, name: Optional[str] = None, db=Depends(get_db)):
    lister = get_compute_lister(
        db,
        page=page,
        size=size
    )

    res = lister.list()
    return JSONResponse(content=jsonable_encoder(BaseRes(data=res)))


@compute_router.post('/compute/add')
async def add_compute(rq: AddComputeReq, db=Depends(get_db)):
    creator = get_compute_creator(
        db, rq.ComputeType, rq.ComputeScale, rq.mainNodeMemory, rq.slaveNodeMemory)
    service_id = creator.create()
    return JSONResponse(content=jsonable_encoder(BaseRes(data=AddComputeRes(serviceID=service_id))))


@compute_router.post('/compute/del')
async def del_compute(rq: DeleteComputeReq, db=Depends(get_db)):
    deleter = get_compute_deleter(db, service_id=rq.serviceID)
    deleter.delete()
    return JSONResponse(content=jsonable_encoder(BaseRes()))


@compute_router.post('/compute/scale')
async def scale_compute(rq: ScaleComputeReq, db=Depends(get_db)):
    scaler = get_compute_scaler(db, rq.service_id, rq.compute_scale)
    res = scaler.scale()
    return JSONResponse(content=jsonable_encoder(BaseRes(data=ScaleComputeRes(service_id=res.service_id))))
